// pages/luoAn/device/deviceMovePath.js
const app = getApp()
const {
  LuoAnHttp,
  Util
} = app.globalData;
const {
  DateFormat
} = Util
const {
  dateObjFormat,
  lastDay,
  moment
} = DateFormat
const lastDayMoment = lastDay(new Date()); // 昨天
const todayDayMoment = moment(new Date()); // 今天
const max = todayDayMoment.format('YYYY-MM-DD HH:mm:ss'); // 可以选最大日期为今天
const startMax = lastDayMoment.format('YYYY-MM-DD HH:mm:ss') // 开始时间最大可选日期为昨天



const dateTimePicker = require('./dateTimePicker.js');
const polylineItem = {
  color: '#46C284',
  width: 10,

  colorList: ['#46C284'],
  borderWidth: 0,
  dottedLine: false,
  arrowLine: true,
  borderWidth: 2,
  borderColor: "#999999",
  points: [{
    latitude: 0,
    longitude: 0
  }, ],
}
const startYear =  2019;
const endYear =  (new Date()).getFullYear()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    path: [polylineItem],
    includePoints: [],


    date: '2019-01-01',
    time: '12:00',
    startTimeArray: null,
    startTimeIndex: null,

    endTimeArray: null,
    endTimeIndex: null,
    

  },

  initDate:function(){
    var obj = dateTimePicker.dateTimePicker(startYear, endYear,startMax);
    var obj1 = dateTimePicker.dateTimePicker(startYear, endYear,max);
    // 精确到分的处理，将数组的秒去掉
    // var lastArray = obj1.dateTimeArray.pop();
    // var lastTime = obj1.dateTime.pop();
    
    this.setData({
      startTimeIndex: obj.dateTime,
      startTimeArray: obj.dateTimeArray,

      endTimeArray: obj1.dateTimeArray,
      endTimeIndex: obj1.dateTime
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    this.initDate();
    const eventChannel = this.getOpenerEventChannel();

    // 请求上一个页面传参数过来
    eventChannel && eventChannel.on && eventChannel.on('param', function (model) {
      let arr = [0, 0];
      if (model.longitudeandlatitude) {
        arr = model.longitudeandlatitude.split(',');
      }
      const {startTimeArray,startTimeIndex,endTimeArray,endTimeIndex} = that.data
      debugger
      that.loadPath({
        starttime:`${startTimeArray[0][startTimeIndex[0]]}-${startTimeArray[1][startTimeIndex[1]]}-${startTimeArray[2][startTimeIndex[2]]} ${startTimeArray[3][startTimeIndex[3]]}:${startTimeArray[4][startTimeIndex[4]]}:${startTimeArray[5][startTimeIndex[5]]}`,
        endtime: `${endTimeArray[0][endTimeIndex[0]]}-${endTimeArray[1][endTimeIndex[1]]}-${endTimeArray[2][endTimeIndex[2]]} ${endTimeArray[3][endTimeIndex[3]]}:${endTimeArray[4][endTimeIndex[4]]}:${endTimeArray[5][endTimeIndex[5]]}`,
        deviceid: model.deviceid
      })
      that.setData({
        model: model,
        lastLatitude: arr[1],
        lastLongitude: arr[0],
      })
    })

  },
  changeDate(e){
    this.setData({ date:e.detail.value});
  },
  changeTime(e){
    this.setData({ time: e.detail.value });
  },
  startChangeDateTime(e){
    const startTimeIndex = e.detail.value;
    this.setData({ startTimeIndex: startTimeIndex });
    const {startTimeArray,endTimeArray,endTimeIndex,model} = this.data
    this.loadPath({
      starttime:`${startTimeArray[0][startTimeIndex[0]]}-${startTimeArray[1][startTimeIndex[1]]}-${startTimeArray[2][startTimeIndex[2]]} ${startTimeArray[3][startTimeIndex[3]]}:${startTimeArray[4][startTimeIndex[4]]}:${startTimeArray[5][startTimeIndex[5]]}`,
      endtime: `${endTimeArray[0][endTimeIndex[0]]}-${endTimeArray[1][endTimeIndex[1]]}-${endTimeArray[2][endTimeIndex[2]]} ${endTimeArray[3][endTimeIndex[3]]}:${endTimeArray[4][endTimeIndex[4]]}:${endTimeArray[5][endTimeIndex[5]]}`,
      deviceid: model.deviceid
    })
  },

  startChangeDateTimeColumn(e){
    var arr = this.data.startTimeIndex, dateArr = this.data.startTimeArray;

    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

    this.setData({
      startTimeArray: dateArr,
      startTimeIndex: arr
    });
  },
  endChangeDateTimeColumn(e) {
    var arr = this.data.endTimeIndex, dateArr = this.data.endTimeArray;

    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

    this.setData({ 
      endTimeArray: dateArr,
      endTimeIndex: arr
    });
  },

  endchangeDateTime(e){
    const endTimeIndex = e.detail.value;
    this.setData({ endTimeIndex: endTimeIndex });
    const {startTimeArray,endTimeArray,startTimeIndex,model} = this.data
    this.loadPath({
      starttime:`${startTimeArray[0][startTimeIndex[0]]}-${startTimeArray[1][startTimeIndex[1]]}-${startTimeArray[2][startTimeIndex[2]]} ${startTimeArray[3][startTimeIndex[3]]}:${startTimeArray[4][startTimeIndex[4]]}:${startTimeArray[5][startTimeIndex[5]]}`,
      endtime: `${endTimeArray[0][endTimeIndex[0]]}-${endTimeArray[1][endTimeIndex[1]]}-${endTimeArray[2][endTimeIndex[2]]} ${endTimeArray[3][endTimeIndex[3]]}:${endTimeArray[4][endTimeIndex[4]]}:${endTimeArray[5][endTimeIndex[5]]}`,
      deviceid: model.deviceid
    })
  },





  loadPath: async function (param) {
    const start = moment(param.starttime);
    const end = moment(param.endtime);
    if(end.isBefore(start)){
      wx.showToast({
        icon:'none',
        title: '启始时间大于终止时间了',
      })
      return
    }
    debugger
    const res = await LuoAnHttp.asyncDevicePath({
      deviceid: param.deviceid,
      starttime: param.starttime,
      endtime: param.endtime
    });
    if (res && res.data) {
      const polyline = {
        ...polylineItem,
        points: res.data.map(v => {
          const longitudeandlatitudeStr = v.longitudeandlatitude;
          const longitudeandlatitudeArr = longitudeandlatitudeStr.split(',')
          if (longitudeandlatitudeArr.length == 2) {
            const latitude = parseFloat(longitudeandlatitudeArr[1]);
            const longitude = parseFloat(longitudeandlatitudeArr[0]);
            return {
              latitude: latitude,
              longitude: longitude
            }
          } else {
            return {
              latitude: 0,
              longitude: 0
            }
          }
        })
      };
      console.log('polyline', polyline)
      this.setData({
        path: polyline.points.length > 0 ? [polyline] : [],
        includePoints: polyline.points
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  startChanged: function (e) {
    this.setData({
      startDate: e.detail.value
    })
    console.log(e);
    this.loadPath({
      deviceid: this.data.model.deviceid,
      starttime: e.detail.value,
      endtime: this.data.endDate
    })
  },
  endChanged: function (e) {
    console.log(e);
    this.setData({
      endDate: e.detail.value
    })
    this.loadPath({
      deviceid: this.data.model.deviceid,
      endtime: e.detail.value,
      starttime: this.data.startDate
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  popMethod: function (e) {
    let pages = getCurrentPages();
    if (pages.length > 1) {
      wx.navigateBack();
    } else {
      wx.reLaunch({
        url: '/pages/luoAn/device/deviceIndex',
      })
    }
  }
})